﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using KC.ExtensionMethods;

namespace KC.Business.Web
{
	public class RequestTools
	{
		public static bool isSearchEngineReferral(Uri Referrer, out string Engine, out string Query)
		{
			Engine = null;
			Query = null;

			if (Referrer == null || string.IsNullOrEmpty(Referrer.AbsoluteUri))
				throw new ArgumentNullException("Referrer");

			if (!Referrer.AbsoluteUri.Contains('?'))
				return false;

			// ParseQueryString doesn't detect the first param('?'); only subsequent params('&')
			// This fools the querystring parser into working right - i.e. into not skipping the first param
			System.Collections.Specialized.NameValueCollection QueryString = HttpUtility.ParseQueryString(Referrer.AbsoluteUri.Replace("?", "?randomxx-8f8d989af&"));
			string QueryMember = "";
			Engine = Referrer.GetRootDomain().ToLower();

			// Determine the QueryMember; i.e. the QueryString key that represents the search term for a given search engine.
			// The great thing about standards is that we have so many of them. Why can't we all do something the same way?
			switch (Engine)
			{	
				case "google.com":
				case "live.com":
				case "msn.com":
				case "altavista.com":
				case "search.com":
				case "ask.com":
				case "cuil.com":
				case "bing.com":
					QueryMember = "q";
					break;
				case "yahoo.com":
					QueryMember = "p";
					break;
				case "lycos.com":
				case "business.com":
				case "aol.com":
				case "netscape.com":
				case "clusty.com":
					QueryMember = "query";
					break;
				case "baidu.com":
					QueryMember = "wd";
					break;
			}
			if (string.IsNullOrEmpty(QueryMember) || string.IsNullOrEmpty(QueryString[QueryMember]))
				return false;
			if (Engine.Contains('.'))
				Engine = Engine.Substring(0, Engine.IndexOf('.'));

			Query = HttpUtility.UrlDecode(QueryString[QueryMember].Trim());
			return true;
		}

	}
}
